package com.itheima.aop;

import cn.hutool.json.JSONUtil;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.annotation.Annotation;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;

@Aspect
@Component
@RequiredArgsConstructor//必须要原本用@Autowired，换成前面加final，一样的效果
public class OperateLogAspect {

    //@Autowired
    final OperateLogMapper operateLogMapper;
    //@Autowired
    final HttpServletRequest request;


    //@Around("execution(public * com.itheima.controller.*.*(..))")
    @Around("@annotation(com.itheima.Log.Log)")
    public Object operatelog(ProceedingJoinPoint pij) throws Throwable {
        long start = System.currentTimeMillis();

        Object proceed = pij.proceed();
        long end = System.currentTimeMillis();

        OperateLog operateLog = new OperateLog();

        //HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

        //从请求头中获取token，获取用户id
        String token = request.getHeader("token");
        Map<String, Object> jwt = JwtUtils.Jwt(token);
        String id = jwt.get("id").toString();

        operateLog.setOperateUser(Integer.valueOf(id));//操作人->jwt->请求头->请求对象
        //operateLog.setOperateEmpId(Integer.valueOf(id));

        MethodSignature signature = (MethodSignature) pij.getSignature();


        Annotation[] annotations = signature.getClass().getAnnotations();
        System.out.println("==================================================" + annotations);
        System.out.println("==================================================" + annotations);
        System.out.println("==================================================" + annotations);


        //operateLog.setOperateUser(12);//操作人
        operateLog.setClassName(pij.getTarget().getClass().getName());//目标类名称
        operateLog.setMethodName(pij.getSignature().getName());//获取方法名称
        operateLog.setMethodParams(JSONUtil.toJsonStr(pij.getArgs()));//获取参数
        operateLog.setReturnValue(JSONUtil.toJsonStr(proceed));//获取返回值
        operateLog.setOperateTime(LocalDateTime.now());//获取修改时间
        operateLog.setCostTime(end - start);//获取方法的执行时间

        operateLogMapper.insert(operateLog);
        return proceed;
    }
}
